package common

import (
	"context"
	"encoding/json"
	"github.com/gorhill/cronexpr"
	"strings"
	"time"
)

type Job struct {
	JobName string `json:"jobName"`
	Command string `json:"command"`
	Exp string `json:"exp"`
}

type Worker struct {
	Ip string `json:"ip"`
}

// 任务执行结果
type JobExecutorResult struct {
	ExecutorInfo *JobExecuteInfo  // 执行状态
	Output []byte  // 执行输出
	Err error
	StartTime time.Time // 执行开始时间
	EndTime time.Time  // 执行结束时间

}
type LogBatch struct {
	Logs []interface{}
}

type JobLog struct {
	JobName string `json:"jobName" bson:"jobName"`
	Command string `json:"command" bson:"command"`
	Err string `json:"err" bson:"err"`
	Output string `json:"output" bson:"output"`
	PlanTime int64 `json:"planTime" bson:"planTime"`  // 计划调度时间
	SchedulerTime int64 `json:"schedulerTime" bson:"schedulerTime"`  // 实际调度时间
	StartTime int64 `json:"startTime" bson:"startTime"`  // 任务开始时间
	EndTime int64 `json:"endTime" bson:"endTime"` // 任务结束时间
}

type JobEvent struct {
	EventType int
	Job *Job
}

// 任务调度计划
type JobSchedulerPlan struct {
	Job *Job
	Expr *cronexpr.Expression
	NextTime time.Time
}

// 任务执行信息
type JobExecuteInfo struct {
	Job *Job
	PlanTime time.Time  // 计划执行时间
	RealTime time.Time  // 实际执行时间
	Ctx context.Context
	CancelFunc context.CancelFunc
}

type Response struct {
	Code int `json:"code"`
	Msg string `json:"msg"`
	Data interface{} `json:"data"`
}

// 构建返回值
func BuildResponse(code int, msg string, data interface{}) (resByte []byte) {
	var (
		resp *Response
	)
	resp = &Response{
		Code: code,
		Msg:  msg,
		Data: data,
	}
	resByte,_ = json.Marshal(resp)
	return
}


func BuildJobEvent(eventType int, job *Job) *JobEvent {
	return  &JobEvent{
		EventType: eventType,
		Job:       job,
	}
}

func UnPackJob(value []byte) (job *Job,err error) {
	job = &Job{}
	err = json.Unmarshal(value,job)
	return
}

func GetJobNameByKey(key []byte) string {
	return strings.TrimPrefix(string(key),ETCD_KEY_PREFIX)
}

func GetIpAddrByKey(key []byte) string {
	return strings.TrimPrefix(string(key),ETCD_JOB_REGISTER_DIR)
}

func GetKillJobNameByKey(key []byte) string {
	return strings.TrimPrefix(string(key),ETCD_KILL_KEY_PREFIX)
}